<?php

namespace MoChat\App\Statistic\Action\Call;

use Hyperf\Database\Model\Model;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Arr;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 呼叫汇总统计
 * @Controller
 */
class CallTotal extends AbstractAction
{

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticCall/total", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $record = $this->callRecord($data);
        return [
            "totalNumber" => $record->totalNumber ?? 0,
            "callOutNumber" => $record->callOutNumber ?? 0,
            "callOutAnswerNumber" => $record->callOutAnswerNumber ?? 0,
            "callInNumber" => $record->callInNumber ?? 0,
            "callInAnswerNumber" => $record->callInAnswerNumber ?? 0,
            "callOutDuration" => $record->callOutDuration ?? 0,
            "callInDuration" => $record->callInDuration ?? 0,
            "missedConnection" => $record->missedConnection ?? 0,
        ];
    }

    /**
     * @param $data
     * @return Model|Builder|mixed|object|null
     */
    private function callRecord($data)
    {
        return Db::table('work_employee as employee')
            ->join('user as user', 'user.id', '=', 'employee.log_user_id')
            ->leftJoin('work_department as dept', 'dept.id', '=', 'employee.main_department_id')
            ->leftJoin('call_record as record', 'record.user_id', '=', 'user.id')
            ->when(!empty($data['deptId']), function ($query) use ($data) {
                $query->where('dept.id', $data['deptId']);
            })
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('record.created_time', [$data['startTime'], $data['endTime']]);
            })
            ->select([
                Db::raw('COUNT(*) as totalNumber'),//总通话数（呼出+呼入）
                Db::raw('COUNT(mc_record.call_type="out" or null) as callOutNumber'),//呼出总量
                Db::raw('COUNT((mc_record.call_duration > 0 && mc_record.call_type="out") or null) as callOutAnswerNumber'),//呼出接听量
                Db::raw('COUNT(mc_record.call_type="in" or null) as callInNumber'),//呼入总量
                Db::raw('COUNT((mc_record.call_duration > 0 && mc_record.call_type="in") or null) as callInAnswerNumber'),//呼入接听量
                Db::raw('SUM(if(mc_record.call_type="out",call_duration,0)) as callOutDuration'),//呼出总时长
                Db::raw('SUM(if(mc_record.call_type="in",call_duration,0)) as callInDuration'),//呼入总时长
                Db::raw('COUNT((mc_record.call_duration = 0 && mc_record.call_type="out") or null) as missedConnection'),//振铃未接呼出数
            ])->first();
    }
}
